from enum import IntEnum, unique

import flask_bcrypt as bcrypt
import peewee as pw

from db.base_model import BaseModel


class User(BaseModel):
    @unique
    class Status(IntEnum):
        INACTIVE = 0
        ACTIVE = 1

    user_id = pw.CharField(max_length=128, unique=True, null=False)
    user_name = pw.CharField(max_length=128, null=False, unique=True)
    password_hash = pw.CharField(max_length=128, null=False)
    content_count = pw.IntegerField(default=0)
    word_count = pw.BigIntegerField(default=0)
    status = pw.SmallIntegerField(default=Status.ACTIVE.value)

    class Meta:
        table_name = "user"

    @property
    def password(self):
        raise AttributeError("password: write-only field")

    @password.setter
    def password(self, password):
        # 用来保存密码hash值
        self.password_hash = bcrypt.generate_password_hash(password).decode("utf-8")

    def check_password(self, password):
        """
        return boolean
        """
        # 判断传过来的密码是否与数据库存的密码一致
        return bcrypt.check_password_hash(self.password_hash, password)
